package com.anoyi.controller.service;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class DyService {

    private final static String VIDEO_WEB_URL = "https://www.iesdouyin.com/share/video/%s/?region=&mid=%s&u_code=14l0k0kmb&titleType=title";

    private final static String UA = "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1";

    public String getUidByVid(String vid) throws IOException {
        String url = String.format(VIDEO_WEB_URL, vid, vid);
        Document document = Jsoup.connect(url).header("user-agent", UA).get();
        return match(document.select("script").html(), "uid: \"([0-9]+?)\"");
    }

    /**
     * 正则匹配
     */
    private String match(String content, String regx){
        Matcher matcher = Pattern.compile(regx).matcher(content);
        if (matcher.find()){
            return matcher.group(1);
        }
        return "";
    }

}
